package com.xuecheng.content.service.iml;

import cn.hutool.core.bean.BeanUtil;
import com.xuecheng.base.execption.CommonError;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.messagesdk.service.impl.MqMessageServiceImpl;
import com.xuecheng.messagesdk.po.MqMessage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CoursePublishServiceImpl implements CoursePublishService {
    @Autowired(required = false)
    CourseBaseMapper courseBaseMapper;
    @Autowired
      CourseBaseServiceIml courseBaseServiceIml;
    @Autowired
      TeachplanServiceIml teachplanServiceIml;
    @Autowired(required = false)
    CoursePublishMapper coursePublishMapper;
    @Autowired(required = false)
    CoursePublishPreMapper coursePublishPreMapper;
    @Autowired
    MqMessageServiceImpl mqMessageService;
    @Autowired
    MediaServiceClient mediaServiceClient;

    /**
     * 课程预览
     *
     * @param courseId
     * @return
     */
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        //课程基本信息、营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseServiceIml.getCourseBaseInfo(courseId);
        //课程计划信息
        List<TeachplanDto> teachplanTree = teachplanServiceIml.queryTeachplanTreeNodes(courseId);

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);
        return coursePreviewDto;
    }



    /**
     * 发布课程
     * @param courseId 课程id
     * @param companyId 机构id
     */
    @Override
    @Transactional
    public void coursepublish(Long courseId, Long companyId) {

        //课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre==null){
            XueChengPlusException.cast("未提交审核，请先提交审核");
        }
        //本机构只允许发布本机构的课程。
        if(!coursePublishPre.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("只允许本机构发布课程");
        }
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //审核通过方可发布
        if(!"202004".equals(courseBase.getAuditStatus())){
            XueChengPlusException.cast("操作失败，课程审核通过方可发布。");
        }


        //向课程发布表course_publish插入一条记录,记录来源于课程预发布表，如果存在则更新，发布状态为：已发布。
        saveCoursePublish(courseId);

        //保存消息表
        saveCoursePublishMessage(courseId);

        //删除课程预发布表对应记录
        coursePublishPreMapper.deleteById(courseId);

    }

    @Override
    public void coursedown(Long courseId) {

    }

    /**
     * 课程静态化
     * @param courseId  课程id
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {
        File htmlFile=null;
        try{
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = getCoursePreviewInfo(courseId);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println(content);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        }catch (Exception e){
            log.error("课程静态化异常:{}",e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }
        return htmlFile;
    }

    /**
     * 上传课程静态化页面
     * @param courseId
     * @param file  静态化文件
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String course = mediaServiceClient.upload(multipartFile,"" ,"course/"+courseId+".html");
        if(course==null){
            file.delete();
            XueChengPlusException.cast("上传静态文件异常");
        }
    }

    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        log.info("{}",coursePublish);
        return coursePublish ;
    }

    //保存消息表
    private void saveCoursePublishMessage(Long courseId) {

        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if(mqMessage==null){
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }

    //保存课程发布表，更新课程表
    private void saveCoursePublish(Long courseId) {
        //查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        CoursePublish publish = new CoursePublish();
        //判断发布表中是否存入数据
        if(coursePublish==null){
            publish.setStatus("203002");
            BeanUtil.copyProperties(coursePublishPre,publish);
            coursePublishMapper.insert(publish);
        }else {
            publish.setStatus("203002");
            coursePublishMapper.updateById(publish);
        }
        //更新课程基本表的发布状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);
    }


}
